var _tableId;
var _table;
var _tbody;
var _headers;
var _searchHeaders = [];

function initTableHeaders(tableId, headers) {
	_tableId = tableId;
	_headers = headers;
	initSearchHeaders(_headers);
	// var table = $('#'+tableId);
	var table = document.getElementById(tableId);
	_table = table;
	
	buildHeaders(headers, table);	
	var tby = document.createElement('tbody');
	_table.appendChild(tby);
	_tbody = document.getElementById(tableId).getElementsByTagName('tbody')[0];
	loadRows();
	
	rowSelection();
}

function buildHeaders(headers, table) {
	var thead = table.createTHead();	
	var row  = thead.insertRow(0);

	$.each(headers, function(idx, value) {	 
		var cell = row.insertCell(idx);
		cell.innerHTML = value;
	});
}

function insertRow(rowData) {
	var tbody = document.getElementById(_tableId).getElementsByTagName('tbody')[0];	
	var row = tbody.insertRow(tbody.rows.length);	
	var i = 0;
	for (var prop in rowData) {				
		row.id = rowData.id;
		var cell = row.insertCell(i);
		cell.innerHTML = rowData[( _searchHeaders[i] )];
		i++;
	}
}

function getRowData() {
	var data = [];
	
	$.ajax({
		type: "GET",
		url: 'user/getList',
		success: function(response) {
			data = response;
		},
		error: function(e) {
			alert('Error: ' + e);				
		},
		async: false
	});	
	return data;
}

function loadRows(rowData, table) {
	var rows  = getRowData();

	$.each(rows, function(idx, value) {	 
		insertRow(value);

	});	
}

function initSearchHeaders(headerArr) {
	for (var i = 0; i < _headers.length; i++) {
		_searchHeaders[i] = _headers[i].toLowerCase();
	}
};

var getEditControls = function() {	
	var controls = '<div class="form-group sub-button-group" style="padding-top: 30px;margin-left:0px; position: inherit">'
		+ '<button type="button" class="btn btn-success" type="submit" onclick="addUser("${addUserURL}")">Save</button>'
		+ '<button type="button" class="btn btn-warning" onclick="updateGoogleMapServerConfigurationGUI()">Delete</button>'
		+ '</div>';
	
	return controls;
};

var selectedRow;
function rowSelection() {
	$('tr').not('thead tr').click(function() {
		if (selectedRow) { 
			selectedRow.removeClass('success');
		};
		
		selectedRow = $(this);
		selectedRow.addClass('success');

		selectedRow.find('td:last').after(getEditControls());
	});
};


